package com.miracle9.game.dao;

import com.miracle9.game.entity.Notice;
import com.miracle9.game.util.MyUtil;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

@Repository
public class NoticeServiceDao extends SqlOperating<Notice, Integer> {

    @Cacheable(value = {"springCache"}, key = "'getNewNotice'")
    public Notice getNoticeByType() {
        Query query = q_CreateSql("from Notice where type=0", new Object[0]);
        query.setMaxResults(1);
        Notice n = (Notice) query.uniqueResult();
        if (n == null) {
            n = new Notice();
            n.setType(0);
            n.setTitle("welcome");
            n.setAdmin("admin");
            n.setContent("welcome");
            n.setDatetime(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
            n.setRangeType(-1);
            saveReturnInteger(n);
            query = q_CreateSql("from Notice where type=0", new Object[0]);
            query.setMaxResults(1);
            n = (Notice) query.uniqueResult();
        }
        return n;
    }

    @CacheEvict(value = {"springCache"}, key = "'getNewNotice'")
    public void updateNotice(String title, String content) {
        q_CreateSql("update Notice set title=?,content=? where type=0", new Object[]{title, content}).executeUpdate();
    }

    @Cacheable(value = {"springCache"}, key = "'getNoticeList'")
    public List<Notice> getNoticesByType() {
        return q_CreateSqlList("from Notice where type=1 order by datetime desc", new Object[0]);
    }

    @CacheEvict(value = {"springCache"}, key = "'getNoticeList'")
    public Integer saveReturnInteger(Notice notice) {
        return (Integer) saveReturn(notice);
    }

    @CacheEvict(value = {"springCache"}, key = "'getNoticeList'")
    public void deleteById(int id) {
        deleteById(Integer.valueOf(id));
    }

    public void deletePastNotice(String date) {
        q_CreateSql("delete from Notice where datetime<?", new Object[]{date}).executeUpdate();
    }

}